package com.ropeok.dao.impl;

import com.ropeok.dao.UserDao;
import com.ropeok.entity.Role;
import com.ropeok.entity.User;
import com.ropeok.util.c3p0Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    Connection connection=c3p0Util.getConnection();//试图获得在service中用c3p0工具类存放在Threadlocal中的connect,不过似乎没成功

    @Override
    public List<User> FindAll() {
        List<User> list=new ArrayList<>();
        try{
            PreparedStatement preparedStatement= connection.prepareStatement("select *from t_user");
            ResultSet resultSet = preparedStatement.executeQuery();
            User user;
            while (resultSet.next()){
                user=new User(); //实例化对象，避免创建的都是同一对象
                user.setUserid(resultSet.getInt("userid"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                list.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void Save(User user) {
        try{
            PreparedStatement preparedStatement=connection.prepareStatement("insert into t_user values (?,?,?)");
            preparedStatement.setInt(1,user.getUserid());
            preparedStatement.setString(2,user.getUsername());
            preparedStatement.setString(3,user.getPassword());
            preparedStatement.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }

    }


    @Override
    public void UpdateUser(User user) {
    }

    @Override
    public void DelUser(int id) {
        try{
            PreparedStatement pstm1=connection.prepareStatement("delete from t_permissions where userid=?");
            pstm1.setInt(1,id);
            pstm1.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }

    }
}
